function createShader(gl, type, source) {
    const shader = gl.createShader(type);
    gl.shaderSource(shader, source);
    gl.compileShader(shader);
    const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
    if (status)
        return shader;
    console.log(gl.getShaderInfoLog(shader));
    gl.deleteShader(shader);
}

function createProgram(vertexShader, fragmentShader) {
    const program = gl.createProgram();
    gl.attachShader(program, vertexShader);
    gl.attachShader(program, fragmentShader);
    gl.linkProgram(program);
    const status = gl.getProgramParameter(program, gl.LINK_STATUS);
    if (status)
        return program;
    console.log(gl.getProgramInfoLog(program));
    gl.deleteProgram(program);
}
// （1 获取上下文
const canvas = document.getElementById("c");
const gl = canvas.getContext("webgl");
if (!gl) {
    console.log("can not use webgl");
}
//  （2 创建着色器
const vertexShaderSource = document.getElementById("vertex-shader").text;
const fragmentShaderSource = document.getElementById("fragment-shader").text;
const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource);
const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource);
// （3 关联两个着色器到着色程序
const program = createProgram(vertexShader, fragmentShader);


// （4 获取顶点着色器在内存中的位置
const vertexLocation = gl.getAttribLocation(program, "a_position");
const colorLocation = gl.getAttribLocation(program, "a_color");
// （5 创建一个缓存，将顶点坐标放入，以便着色器适用
const positionBuffer = gl.createBuffer();
// （10 用缓存的顶点坐标

gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
// 超过 1 就会超出画布
const posData = [
    0, 0,
    0, -1,
    0.7, 0
];
// 写数据
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(posData), gl.STATIC_DRAW);
gl.enableVertexAttribArray(vertexLocation);

// （11 定点着色器开始读数据
// gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
const size = 2; 
const type = gl.FLOAT;
const normalize = false; // 归一化 
const stride = 0; // 
const offset = 0; //起始位置
gl.vertexAttribPointer(vertexLocation, size, type, normalize, stride, offset);

const colorBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
const colorData = new Float32Array([
    1.0, 0, 0, 1,
    0, 1.0, 0, 1,
    0, 0, 1.0, 1
]);
gl.bufferData(gl.ARRAY_BUFFER, colorData, gl.STATIC_DRAW);
gl.enableVertexAttribArray(colorLocation);
const csize = 4; 

gl.vertexAttribPointer(colorLocation, csize, gl.FLOAT, false, 0, 0);

// （7 传递画布大小
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
console.log(canvas.width, gl.canvas.height);
// （8 画布颜色
gl.clearColor(255, 0, 255, 255);
gl.clear(gl.COLOR_BUFFER_BIT);

// （9 运行着色器
gl.useProgram(program);

// （13 指定画的类型
const graType = gl.TRIANGLES;
const pointOffset = 0; // 从第几个点开始画
const count = 3; // 需要画几个点
// （14 画顶点
gl.drawArrays(graType, pointOffset, count);